/**
 * @Date 14-11-2013
 * Class used to manage file downloads using FTP
 */
package com.globalblue.ftp;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class FTPDownloader {
	public static final Logger logger = Logger.getLogger(FileOutputStream.class);

	FTPClient ftp = null;

	/**
	 * Constructor of the class. create FTP connection and login 
	 * @param host
	 * @param user
	 * @param pwd
	 * @throws Exception
	 */
	public FTPDownloader(String host, String user, String pwd) throws Exception {
		ftp = new FTPClient();
		//ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.getProperty("catalina.base")+"/logs/testlog.log")));
		int reply;
		ftp.connect(host, 21);
		reply = ftp.getReplyCode();
		if (!FTPReply.isPositiveCompletion(reply)) {
			ftp.disconnect();
			throw new Exception("Exception in connecting to FTP Server");
		}
		ftp.login(user, pwd);
		ftp.setFileType(FTP.ASCII_FILE_TYPE);
		ftp.enterLocalPassiveMode();
	}

	/**
	 * Download the required file
	 * @param remoteFilePath
	 * @param localFilePath
	 */
	public void downloadFile(String remoteFilePath, String localFilePath) {
		try {
			FileOutputStream fos = new FileOutputStream(localFilePath);
			this.ftp.retrieveFile(remoteFilePath, fos);
		} catch (IOException e) {
			logger.log(Level.ERROR, e);
		}
	}

	/**
	 * Disconnect from server
	 */
	public void disconnect() {
		if (this.ftp.isConnected()) {
			try {
				this.ftp.logout();
				this.ftp.disconnect();
			} catch (IOException f) {
				logger.log(Level.ERROR, f);
			}
		}
	}

	/*public static void main(String[] args) {
		try {
			String host = "localhost";
			FTPDownloader ftpDownloader = new FTPDownloader(host, "uwijekoon", "usw#8486@GB");
			ftpDownloader.downloadFile("\\GripsCoordinator_13_03\\GripsCoordinator.WindowsServiceHost.exe.config", "C:/servicesFiles/applicationHost_" + host + ".config");
			System.out.println("FTP File downloaded successfully");
			ftpDownloader.disconnect();
		} catch (Exception e) {
			logger.log(Level.ERROR, e);
		}
	}*/

}
